package cn.car91.activity;

import java.util.Date;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.adapter.CommentListAdapter;
import cn.car91.bean.Exposure;
import cn.car91.bean.ExposureComment;
import cn.car91.bean.User;
import cn.car91.http.HttpHandler;
import cn.car91.pager.CommentPager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.MyListView;
import cn.car91.view.VerticalScrollView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class ExposureDetailActivity extends BaseActivity {
    final int Request_Code = 22002;

    private CommentPager commentPager = new CommentPager();

    ExposureDetailHandler exposureDetailHandler;

    LinearLayout comments;
    VerticalScrollView commentScroll;
    MyListView commentList;

    EditText commentContent;
    Button commentSubmitBtn;

    PopupWindow popupWindow;
    CommentListAdapter<ExposureComment> commentListAdapter;

    String title;
    String eid;

    boolean addDate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_exposure_detail);
        super.onCreate(savedInstanceState);
        initView();

        eid = getIntent().getStringExtra("eid");
        if (RegexUtil.isNotNull(eid)) {
        	HttpHandler.httpHandler.getExposureDetail(eid, callbackDetail);
        }

        comments = (LinearLayout) getLayoutInflater().inflate(R.layout.view_article_comment, null);
        commentContent = (EditText) comments.findViewById(R.id.article_detail_comment_content);
        commentSubmitBtn = (Button) comments.findViewById(R.id.article_detail_comment_submit);
        comments.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                comments.requestFocus();
                return false;
            }
        });
        commentSubmitBtn.setOnClickListener(onSubmitClickListener);

        commentList = (MyListView) comments.findViewById(R.id.article_detail_comment_list);
        commentListAdapter = new CommentListAdapter(ExposureDetailActivity.this, R.layout.view_article_comment_item);
        commentList.setAdapter(commentListAdapter);

        commentScroll = (VerticalScrollView) comments.findViewById(R.id.article_detail_comment_scroll);
        commentScroll.setOnTouchListener(onScrollTouchListener);
    }

    /* 详情页面 */
    private class ExposureDetailHandler {
        public TextView exposureTitle;
        public TextView exposureTime;
        public TextView exposureAuthor;
        public WebView exposureContent;
        public TextView exposureScan;
        public TextView exposureRepairShop;
        public TextView exposureAddress;
    }

    private void initView() {
        exposureDetailHandler = new ExposureDetailHandler();
        exposureDetailHandler.exposureTitle = (TextView) findViewById(R.id.exposure_detail_title);
        exposureDetailHandler.exposureTime = (TextView) findViewById(R.id.exposure_detail_time);
        exposureDetailHandler.exposureAuthor = (TextView) findViewById(R.id.exposure_detail_author);
        exposureDetailHandler.exposureContent = (WebView) findViewById(R.id.exposure_detail_content);
        exposureDetailHandler.exposureScan = (TextView) findViewById(R.id.exposure_detail_scan);
        exposureDetailHandler.exposureRepairShop = (TextView) findViewById(R.id.exposure_detail_repairshop);
        exposureDetailHandler.exposureAddress = (TextView) findViewById(R.id.exposure_detail_address);
        exposureDetailHandler.exposureContent.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        exposureDetailHandler.exposureContent.getSettings().setGeolocationEnabled(true);
    }

    /**
     * 页面显示商家信息
     *
     * @param exposure 商家
     */
    private void initData(Exposure exposure) {
        if (exposureDetailHandler != null && exposure != null) {
            title = exposure.getTitle();
            exposureDetailHandler.exposureTitle.setText(title);

            exposureDetailHandler.exposureTime.setText(DateFormat.format("yy-MM-dd kk:mm", exposure.getTime()));

            if (exposure.getUname() != null)
                exposureDetailHandler.exposureAuthor.setText(exposure.getUname());
            else
                exposureDetailHandler.exposureAuthor.setText(R.string.article_detail_author_default);

            exposureDetailHandler.exposureRepairShop.setText(exposure.getName());
            exposureDetailHandler.exposureAddress.setText(exposure.getAddress());
            exposureDetailHandler.exposureContent.loadDataWithBaseURL(getCar91Application().getExposureServerUrl(), exposure.getReason(), "text/html", "utf-8", null);
            exposureDetailHandler.exposureScan.setText(String.valueOf(exposure.getScan()));

            ((TextView) findViewById(R.id.header_text)).setText(exposure.getTitle());
        } else {
            new HerilyAlertDialog.Builder(ExposureDetailActivity.this)
                    .setMessage("该曝光被限制浏览\n或已被删除")
                    .create().show();
        }
    }

    private OnTouchListener onScrollTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            // TODO Auto-generated method stub
            switch (arg1.getAction()) {
                case MotionEvent.ACTION_UP:
                    doOnBorderListener();
                    break;
            }
            return false;
        }

        private void doOnBorderListener() {
            if (popupWindow != null) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    return;
                }
            }

            if (commentList != null && commentList.getMeasuredHeight() <= commentScroll.getScrollY() + commentScroll.getHeight()) {
                //底部
                addDate = true;
                getData();
            } else if (commentScroll.getScrollY() == 0) {
                //顶部
            }
        }
    };

    /**
     * 回调获取文章详情
     */
    private RequestCallBack callbackDetail = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "网络不给力啊~", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            initData((Exposure) Car91JsonUtil.getDTO(arg0.result.toString(), Exposure.class));
        }
    };

    OnClickListener onSubmitClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            User user = getCar91Application().getUser();
            if (user != null) {
                String content = commentContent.getText().toString();
                if (RegexUtil.isNotNull(content)) {
                	HttpHandler.httpHandler.addExposureComment(eid, user.getId(), content, callBackSubmit);
                } else {
                    new HerilyAlertDialog.Builder(ExposureDetailActivity.this).setMessage("请输入内容").setNegativeButton("确认", null).create().show();
                }
            } else {
                new HerilyAlertDialog.Builder(ExposureDetailActivity.this)
                        .setMessage("请先登录")
                        .setPositiveButton("登录", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent();
                                intent.setClass(ExposureDetailActivity.this, UserLoginActivity.class);
                                startActivityForResult(intent, Request_Code);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create().show();
            }
        }
    };

    private void getData() {
    	commentPager.getExposureComment(eid, callBackComment);
    }

    @OnClick(R.id.comment_btn)
    public void onCommentClick(View arg0) {
        // TODO Auto-generated method stub
        if (comments != null) {
            View parent = findViewById(R.id.exposure_detail);
            if (popupWindow == null) {
                getData();

                popupWindow = new PopupWindow(comments);
                popupWindow.setHeight(parent.getMeasuredHeight());
                popupWindow.setWidth((int) (parent.getMeasuredWidth() * 0.7));
                popupWindow.setAnimationStyle(R.style.article_comment_popu_anim_style);
                // 需要设置一下此参数，点击外边可消失
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                popupWindow.setOutsideTouchable(true);
                //设置弹出窗体需要软键盘，
                popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                //再设置模式，和Activity的一样，覆盖。
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
                popupWindow.setFocusable(true);
                popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 28);
            } else {
                if (!popupWindow.isShowing()) {
                    popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 28);
                }
            }
        }
    }

    RequestCallBack callBackComment = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            List<ExposureComment> comments = Car91JsonUtil.getDTOList(arg0.result.toString(), ExposureComment.class);
            if (comments.size() > 0) {
                if (addDate) {
                    commentListAdapter.addData(comments);
                } else {
                    commentListAdapter.setData(comments);
                }
                commentListAdapter.notifyDataSetChanged();
                addDate = true;
            }
        }
    };

    RequestCallBack callBackSubmit = new RequestCallBack() {
        @Override
        public void onStart() {
            // TODO Auto-generated method stub
            commentSubmitBtn.setEnabled(false);
            commentContent.setEnabled(false);
            super.onStart();
        }

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            commentSubmitBtn.setEnabled(true);
            commentContent.setEnabled(true);
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            if (arg0.result.toString().equals("1")) {
                List<ExposureComment> comments = commentListAdapter.getData();
                ExposureComment comment = new ExposureComment();
                comment.setUsername(getCar91Application().getUser().getName());
                comment.setTime(new Date());
                comment.setContent(commentContent.getText().toString());
                comments.add(0, comment);
                commentListAdapter.setData(comments);
                commentListAdapter.notifyDataSetChanged();

                commentContent.setText("");
                commentSubmitBtn.setEnabled(true);
                commentContent.setEnabled(true);
                ExposureDetailActivity.this.comments.requestFocus();
            } else {
                Toast.makeText(ExposureDetailActivity.this, "发表失败", Toast.LENGTH_SHORT).show();
                commentSubmitBtn.setEnabled(true);
                commentContent.setEnabled(true);
            }

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == Request_Code) {
            switch (resultCode) {
                case Car91ResultCode.Refresh_User_Code:
                    commentSubmitBtn.performClick();
                    break;
                default:
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
